package com.smc.jnidemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    public String myValue = "123";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void call(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void onChangeValueBtn(View v){
        nativeUpdateJavaValue(getClass().getName().replace(".", "/"), "myValue");
        Toast.makeText(this, myValue, Toast.LENGTH_SHORT).show();
    }

    public void onCallMethodBtn(View v){
        nativeCallJavaMethod(getClass().getName().replace(".", "/"),"call");
    }

    public void onCreateObjectBtn(View v){
        Person person = nativeCreateObject(Person.class, 20, "jack", "china");
        Toast.makeText(this, person.toString(), Toast.LENGTH_SHORT).show();
    }

    public void onThreadBtn(View v){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //每一个线程调用jni, 对应的JNIEnv是不同的
                Person person = nativeCreateObject(Person.class, 20, "jack", "china");
                Log.i(TAG, person.toString());
            }
        };
        Thread th = new Thread(runnable);
        th.start();
    }


    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */

    public native int nativeUpdateJavaValue(String className, String fieldName);
    public native int nativeCallJavaMethod(String className, String methodName);
    public native <T> T nativeCreateObject(Class<T> tClass, int age, String name, String addr);
    public native String stringFromJNI();
}
